const ProductModel = require("../../models/ProductModel");
const ProductService = {
  add: async ({ title, introduction, detail, cover }) => {
    return await ProductModel.create({
      title,
      introduction,
      detail,
      cover,
    });
  },

  getListById: async ({ _id }) => {
    return _id ? ProductModel.find({ _id }) : ProductModel.find({});
  },

  getListOfPage: async ({
    searchValue,
    pageNo,
    limit,
    sortField,
    sortOrder,
  }) => {
    // 计算需要跳过的记录数
    const skip = (pageNo - 1) * limit;

    // 构建模糊查询的正则表达式(根据用户名（title）进行模糊查询)
    const searchRegex = new RegExp(searchValue, "i"); // 'i' 表示不区分大小写

    // 查询数据库，并只选择需要的字段
    const records = await ProductModel.find({ title: searchRegex })
      .select("")
      .sort({ [sortField]: sortOrder })
      .skip(skip)
      .limit(limit);

    // 计算基于搜索条件的总记录数
    const total = await ProductModel.countDocuments({ title: searchRegex });

    // 计算总页数
    const pages = Math.ceil(total / limit);

    return {
      records,
      total,
      pages,
    };
  },

  deleteListItem: async ({ _id }) => {
    return ProductModel.deleteOne({ _id });
  },

  putList: async (body) => {
    return ProductModel.updateOne({ _id: body._id }, body);
  },

  publish: async ({ _id, isPublish }) => {
    return ProductModel.updateOne({ _id }, { isPublish });
  },
};

module.exports = ProductService;
